package xin.yangshuai.springsecurity03.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.MessageDigestPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import xin.yangshuai.springsecurity03.entity.SpringSecurityUser;
import xin.yangshuai.springsecurity03.mapper.SpringSecurityUserMapper;
import xin.yangshuai.springsecurity03.service.SpringSecurityUserService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SpringSecurityUserServiceImpl implements SpringSecurityUserService {

    @Autowired
    private SpringSecurityUserMapper springSecurityUserMapper;

    @Override
    public List<SpringSecurityUser> list() {
        return springSecurityUserMapper.selectList(null);
    }

    @Override
    public int add(SpringSecurityUser springSecurityUser) {

        if (springSecurityUser == null) {
            return 0;
        }

        // org.springframework.security.crypto.factory.PasswordEncoderFactories

        String encodingId = "bcrypt";
        Map<String, PasswordEncoder> encoders = new HashMap();
        encoders.put(encodingId, new BCryptPasswordEncoder());
        encoders.put("MD5", new MessageDigestPasswordEncoder("MD5"));
        // ...

        // encodingId = "MD5";
        PasswordEncoder encoder = new DelegatingPasswordEncoder(encodingId, encoders);


        String password = springSecurityUser.getPassword();
        String encode = encoder.encode(password);
        springSecurityUser.setPassword(encode);

        return springSecurityUserMapper.insert(springSecurityUser);
    }
}
